package com.ruoyi.web.cp.service.http;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.web.core.config.ConfigLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-29 16:25
 */
@Slf4j
@Service
public class ObHttpService {
    @Autowired
    private ConfigLoader configLoader;

    /**
     * @Description: 获取ob请求头
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject getObHeaders() {
        List<String> cookie = FileUtil.readLines(configLoader.getGamenamesPath() + "ob-cookie.txt", "utf8");
        JSONObject header = new JSONObject();
        header.put("requestId", cookie.get(0));
        return header;
    }

    /**
     * @Description: 获取ob列表
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject sendObList(JSONArray datas) {
        JSONObject header = getObHeaders();
        JSONObject body = new JSONObject();
        body.put("cuid", "511491216875443815");
        body.put("sort", "2");
        body.put("apiType", "1");
        body.put("orpt", "0");
        body.put("euid", "3020101");

        long time = System.currentTimeMillis();
        String url = ConfigLoader.getConfig().getObHost() + "yewu11/v2/w/structureTournamentMatches?t=" + time;

        JSONArray keys = new JSONArray();
        keys.fluentAdd("mids").fluentAdd("tn");
        JSONObject key = new JSONObject();
        key.put("keys", keys);

        JSONObject data = new JSONObject();
        data.put("datas", datas);

//        return HttpUtils.httpJson(url, "post", body, header);
        return HttpUtils.httpJsonNew("cp/obList", url, "post", body, header, key, data);
    }

    public JSONObject sendObListNew() {
        JSONObject header = getObHeaders();
        JSONObject body = new JSONObject();
        body.put("cuid", "511491216875443815");
        body.put("sort", "2");
        body.put("apiType", "1");
        body.put("orpt", "0");
        body.put("euid", "3020101");

        long time = System.currentTimeMillis();
        return HttpUtils.httpJson(ConfigLoader.getConfig().getObHost() + "yewu11/v2/w/structureTournamentMatches?t=" + time, "post", body, header);
    }


    /**
     * @Description: 获取ob列表
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject sendObBasketList() {
        JSONObject header = getObHeaders();
        JSONObject body = new JSONObject();
        body.put("cuid", "516951543149130708");
        body.put("sort", "1");
        body.put("apiType", "1");
        body.put("orpt", "7");
        body.put("euid", "3020102");

        long time = System.currentTimeMillis();
        return HttpUtils.httpJson(ConfigLoader.getConfig().getObHost() + "yewu11/v2/w/structureTournamentMatches?t=" + time, "post", body, header);
    }

    /**
     * @Description: 获取ob列表详情
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject sendObListDetail(String mid, boolean isUseCache) {
        String filePath = configLoader.getGamenamesPath() + "ob-gameresult/" + mid + ".txt";
        boolean fileExist = FileUtils.isFileExist(filePath);
        if (isUseCache && fileExist) {
            String str = FileUtil.readString(filePath, CharsetUtil.charset("utf8"));
            try {
                JSONObject jsonObject = JSON.parseObject(str);
                if ("0000000".equals(jsonObject.getString("code"))) {
                    return JSONObject.parseObject(str);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        long beginTime = System.currentTimeMillis();
        JSONObject header = getObHeaders();
        String url = ConfigLoader.getConfig().getObHost() + "yewu11/v1/w/matchDetail/getMatchDetail?mid=" + mid + "&cuid=511491216875443815&t=" + beginTime;
//        JSONObject res = HttpUtils.httpJson(url, "get", null, header);

        JSONArray keys = new JSONArray();
        //"mst", "mhn", "man", "tn", "mgt"
        keys.fluentAdd("mst").fluentAdd("mhn").fluentAdd("man").fluentAdd("tn").fluentAdd("mgt");
        JSONObject key = new JSONObject();
        key.put("keys", keys);
        JSONObject res = HttpUtils.httpJsonNew("cp/obListDetail", url, "get", null, header, key);
        FileUtil.writeString(res.toJSONString(), filePath, "utf8");
        log.info("ob列表详情耗时:{}", (System.currentTimeMillis() - beginTime));
        ThreadUtil.sleep(1000);
        res.put("isNew", true);
        return res;
    }

    /**
     * @Description: 获取ob列表详情
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject sendObListBasketDetail(String mid) {
        String filePath = configLoader.getGamenamesPath() + "ob-basket-gameresult/" + mid + ".txt";
        boolean fileExist = FileUtils.isFileExist(filePath);
        if (fileExist) {
            String str = FileUtil.readString(filePath, CharsetUtil.charset("utf8"));
            if (str.length() > 300) {
                return JSONObject.parseObject(str);
            }
        }
        long beginTime = System.currentTimeMillis();
        JSONObject header = getObHeaders();
        String url = ConfigLoader.getConfig().getObHost() + "yewu11/v1/w/matchDetail/getMatchDetail?mid=" + mid + "&cuid=516951543149130708&t=" + beginTime;
        JSONObject res = HttpUtils.httpJson(url, "get", null, header);
        FileUtil.writeString(res.toJSONString(), filePath, "utf8");
        log.info("ob列表详情耗时:{}", (System.currentTimeMillis() - beginTime));
        ThreadUtil.sleep(1000);
        res.put("isNew", true);
        return res;
    }

    /**
     * @Description: 获取ob详情
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public JSONObject sendObDetail(String mid, String game, boolean isUseCache) {
        String filePath = configLoader.getRmPath() + "ob-gamescore/" + mid + ".txt";
        boolean fileExist = FileUtils.isFileExist(filePath);
        if (isUseCache && fileExist) {
            String str = FileUtil.readString(filePath, StandardCharsets.UTF_8);
            if (str.length() > 300) {
                return JSONObject.parseObject(str);
            }
        }

        log.info(game);
        long beginTime = System.currentTimeMillis();
        JSONObject header = getObHeaders();
        String url = ConfigLoader.getConfig().getObHost() + "yewu11/v1/w/matchDetail/getMatchOddsInfo1?mcid=0&mid=" + mid + "&cuid=511491216875443815&newUser=0&t=" + beginTime;
        JSONObject res = HttpUtils.httpJsonNew("cp/obGameDetail", url, "post", null, header);
        FileUtil.writeString(res.toJSONString(), filePath, "utf8");
        log.info("ob详情耗时:{}", (System.currentTimeMillis() - beginTime));
        ThreadUtil.sleep(1000);
        return res;
    }

    public static void main(String[] args) {
//        new ObHttpService().sendObGameResult();
    }

    /**
     * @author xiesm
     * @description OB赛果
     * @date 2025/8/26
     */
    public JSONObject sendObGameResult(Long startTime, Long endTime, int current, List<String> leagueIds) {
        long beginTime = System.currentTimeMillis();
        JSONObject header = getObHeaders();

        String url = "https://api.h8ee0m89.com/yewu11/v1/orderScoreResult/queryTournamentScoreResult?t=" + System.currentTimeMillis();

        JSONObject page = new JSONObject();
        page.fluentPut("current", current)
                .fluentPut("size", 100);

        JSONObject body = new JSONObject();
        body.fluentPut("runningBar", "0")
                .fluentPut("isPlayBack", "0")
                .fluentPut("orderBy", "0")
                .fluentPut("sportType", "1")
                .fluentPut("startTime", startTime)
                .fluentPut("endTime", endTime)
                .fluentPut("langType", "zh")
                .fluentPut("page", page)
                .fluentPut("isVirtualSport", "")
                .fluentPut("matchNameStr", "")
                .fluentPut("isNew", "1")
                .fluentPut("champion", 0)
                .fluentPut("isESport", "")
                .fluentPut("tournamentId", CollUtil.join(leagueIds, ","));

        JSONObject res = HttpUtils.httpJson("http://115.175.26.90:8089/", url, "post", body, header, 10000);
        log.info("ob详情耗时:{}", (System.currentTimeMillis() - beginTime));
        ThreadUtil.sleep(1000);
        System.out.println(res);
        return res;
    }

    /**
     * @author xiesm
     * @description OB联赛id
     * @date 2025/8/26
     */
    public JSONObject sendObGameLeague(Long startTime, Long endTime) {
        long beginTime = System.currentTimeMillis();
        JSONObject header = getObHeaders();

        String url = "https://api.h8ee0m89.com/yewu11/v1/orderScoreResult/queryTournament?t=" + System.currentTimeMillis();

        JSONObject body = new JSONObject();
        body.fluentPut("sportType", "1")
                .fluentPut("startTime", startTime)
                .fluentPut("endTime", endTime)
                .fluentPut("langType", "zh")
                .fluentPut("nameStr", "")
                .fluentPut("hot", null)
                .fluentPut("isVirtualSport", "")
                .fluentPut("runningBar", "0")
                .fluentPut("champion", 0)
                .fluentPut("showem", 1);

        JSONObject res = HttpUtils.httpJson("http://115.175.26.90:8089/", url, "post", body, header, 10000);
        log.info("ob详情耗时:{}", (System.currentTimeMillis() - beginTime));
        ThreadUtil.sleep(1000);
        System.out.println(res);
        return res;
    }
}
